package com.safewind.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.safewind.dao.UserDao;
import com.safewind.model.User;
import com.safewind.service.IUserService;
import com.safewind.service.IValueService;
import com.safewind.util.StringUtil;

@Service("userService")
public class UserServiceImpl implements IUserService {
	@Resource
	private IValueService valueService;

	@Resource
	private UserDao userDao;

	@Override
	public User getUserById(String userId) {
		String md5UserId = StringUtil.toMd5(userId);
		return userDao.selectByPrimaryKey(md5UserId);
	}

	@Override
	public User getUserByMD5Id(String userId) {
		return userDao.selectByPrimaryKey(userId);
	}

	@Override
	public void addUser(User user) {
		userDao.insertSelective(user);
	}

	@Override
	public boolean enoughValue(String userId, int value) {
		int diffValue = userDao.selectByPrimaryKey(userId).getValue() - value;
		if (diffValue > 0) {
			return true;
		}
		return false;
	}

	@Override
	public void updateValue(String userId, int cost, String content) {
		User user = userDao.selectByPrimaryKey(userId);
		int value = user.getValue() + cost;
		user.setValue(value);
		userDao.updateByPrimaryKeySelective(user);
		valueService.insertValue(userId, cost, content);
	}

	@Override
	public void updateUser(User user) {
		userDao.updateByPrimaryKeySelective(user);
	}

}
